package com.article.service.impl;

import com.article.dao.AdminInfoDao;
import com.article.dao.RoleInfoDao;
import com.article.dto.ReturnError;
import com.article.enums.ReturnInfoEnum;
import com.article.model.RoleInfo;
import com.article.service.RoleInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/5/2.
 */
@Service("roleInfoService")
public class RoleInfoServiceImpl implements RoleInfoService {
    @Autowired
    private RoleInfoDao roleInfoDao;
    @Autowired
    private AdminInfoDao adminInfoDao;

    public Long countTotal(Map<String, Object> map) {
        return roleInfoDao.countTotal(map);
    }

    public List<RoleInfo> listByPage(Map<String, Object> map) {
        return roleInfoDao.listByPage(map);
    }

    public List<RoleInfo> listByMap(Map<String, Object> map) {
        return roleInfoDao.listByMap(map);
    }

    public RoleInfo getById(Long id) {
        return roleInfoDao.getById(id);
    }

    public RoleInfo getByMap(Map<String, Object> map) {
        return roleInfoDao.getByMap(map);
    }

    @Transactional
    public ReturnError saveRole(RoleInfo roleInfo) {
        try {
            int result = roleInfoDao.save(roleInfo);
            if (result != 0) {
                return new ReturnError(false, ReturnInfoEnum.SUCCESS.getType(), ReturnInfoEnum.SUCCESS.getInfo(), null);
            }
            return new ReturnError(true, ReturnInfoEnum.FAIL.getType(), "已存在相同角色名", null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Transactional
    public ReturnError updateRole(RoleInfo roleInfo) {
        try {
            int result = roleInfoDao.update(roleInfo);
            if (result != 0) {
                return new ReturnError(false, ReturnInfoEnum.SUCCESS.getType(), ReturnInfoEnum.SUCCESS.getInfo(), null);
            }
            return new ReturnError(true, ReturnInfoEnum.FAIL.getType(), "已存在相同角色名", null);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Transactional
    public ReturnError removeRole(String ids) {
        String[] idarr = ids.split(",");
        try {
            for (String id : idarr) {
                Long roleId = Long.parseLong(id);
                if (roleId.longValue() == 1) {
                    continue;
                }
                int i = roleInfoDao.remove(roleId);
                if (i != 0) {
                    adminInfoDao.removeByRoleId(roleId);
                }
            }
            return new ReturnError(false, ReturnInfoEnum.SUCCESS.getType(), null);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
